package main

import "github.com/gin-gonic/gin"

// ar *AnswerRouter IRouter
type AnswerRouter struct{}

func (ar *AnswerRouter) path() string {
	return "/answer"
}

func (ar *AnswerRouter) get() string {
	return ar.path() + "/:id"
}

func (ar *AnswerRouter) post() string {
	return ar.path()
}

func (ar *AnswerRouter) put() string {
	return ar.path() + "/:id"
}

func (ar *AnswerRouter) delete() string {
	return ar.path() + "/:id"
}

func (ar *AnswerRouter) Find(c *gin.Context) {
	id := c.Param("id")
	if id == "" {
		var answers []Answer
		SqliteDB().Find(&answers)
		done(c, 200, answers)
		return
	}

	var answer Answer
	err := SqliteDB().Where("id = ?", id).First(&answer).Error
	if err != nil {
		done(c, 500, err.Error())
		return
	}
	done(c, 200, answer)
}

func (ar *AnswerRouter) Create(c *gin.Context) {
	var answer Answer
	c.Bind(&answer)

	err := SqliteDB().Create(&answer).Error
	if err != nil {
		done(c, 500, err.Error())
		return
	}
	done(c, 200, answer)
}

func (ar *AnswerRouter) Update(c *gin.Context) {
	id := c.Param("id")
	var answer Answer
	c.Bind(&answer)

	if err := SqliteDB().Where("id = ?", id).Updates(&answer).Error; err != nil {
		done(c, 500, err.Error())
		return
	}
	done(c, 200, answer)
}

func (ar *AnswerRouter) Delete(c *gin.Context) {
	id := c.Param("id")
	if err := SqliteDB().Where("id = ?", id).Delete(&Answer{}).Error; err != nil {
		done(c, 500, err.Error())
		return
	}
	done(c, 200, "success")
}
